package ajaxjs.data.user;

/**
 * 验证码的简单实现
 * http://a455360448201209214217.iteye.com/blog/1953785
 * 调用方式：
 * <%@ page language="java" contentType="image/JPEG; charset=UTF-8" pageEncoding="UTF-8"%>  
<%com.ajaxjs.bigfoot.tools.VcodeImg.init(pageContext);%>
 * @author sp42
 */
public class VcodeImg {
	private java.awt.Color getRandColor(int fc, int bc) {
		java.util.Random random = new java.util.Random();

		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;

		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);

		return new java.awt.Color(r, g, b);
	}
	private int width 	= 60;
	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}
	private int height 	= 20;
	
	private String code = null;
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public java.awt.image.BufferedImage get() {
		java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(
			width, height,
			java.awt.image.BufferedImage.TYPE_INT_RGB
		);
		
		java.awt.Graphics g;
		g = image.getGraphics();
		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);
		g.setFont(new java.awt.Font("Times New Roman", java.awt.Font.PLAIN, 18));
		g.setColor(getRandColor(160, 200));

		java.util.Random random = new java.util.Random();
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}
		String sRand = "";
		for (int i = 0; i < 4; i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand += rand;
			g.setColor(new java.awt.Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(rand, 13 * i + 6, 16);
		}

		// 将认证码存入SESSION
//		session.setAttribute("rand", sRand);
		this.setCode(sRand);
		g.dispose();
		
		return image;
	}
	
	public static void init(javax.servlet.jsp.PageContext pageContext){
		javax.servlet.http.HttpServletResponse response = 
				(javax.servlet.http.HttpServletResponse) pageContext.getResponse();

		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		
		VcodeImg img = new VcodeImg();
		
		pageContext.getSession().setAttribute("rand", img.getCode());// 将认证码存入SESSION
		
		try {
			javax.imageio.ImageIO.write(img.get(), "JPEG", response.getOutputStream());
			
			// 加上下面代码,运行时才不会出现java.lang.IllegalStateException: getOutputStream() has already been called ..........等异常  
			response.getOutputStream().flush();    
			response.getOutputStream().close();    
			response.flushBuffer();
			
//			JSP内置对象out和response.getWrite()的区别，两者的主要区别：1. 这两个对象的类型是完全不同的……
//			response.getWriter();
//			http://blog.sina.com.cn/s/blog_7217e4320101l8gq.html
			
//			http://www.2cto.com/kf/201109/103284.html
			
			pageContext.getOut().clear(); 
		} catch (java.io.IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 判断用户输入的验证码是否通过
	 * @return
	 * @throws Throwable 
	 */
	public Boolean isPass(javax.servlet.jsp.PageContext pageContext) throws Throwable{
		Boolean isCaptchaPass = false;
		
		String rand = (String)pageContext.getSession().getAttribute("rand"), 
				CaptchaCode = pageContext.getRequest().getParameter("CaptchaCode");
		
		System.out.println("rand:" + rand);
		System.out.println("CaptchaCode:" + CaptchaCode);

		if(rand == null)
			throw new Exception("请刷新验证码。");
		else if(CaptchaCode == null || CaptchaCode.equals("")){
			throw new Exception("没提供验证码参数");
		}else{
			isCaptchaPass = rand.equals(CaptchaCode);
			if(!isCaptchaPass)throw new Exception("验证码不正确"); 
		}
		
		return isCaptchaPass;
	}
}
